<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <campus @schoolCampus="searchhandleSchoolCampus" :selectValue="queryParams.schoolCampusId"></campus>

          <el-form-item label="教师姓名" prop="teacherName">
            <el-input v-model="queryParams.teacherName" placeholder="请输入教师姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable>
              <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="入职时间" prop="joinDate">
            <el-date-picker clearable v-model="queryParams.joinDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择入职时间" />
            
          </el-form-item>
          <el-form-item label="民族" prop="nation">
            <el-select v-model="queryParams.nation" placeholder="请选择民族" clearable>
              <el-option v-for="dict in nation" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="在岗状态" prop="onDutyStatus">
            <el-select v-model="queryParams.onDutyStatus" placeholder="请选择在岗状态" clearable>
              <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="在职状态" prop="onJobStatus">
            <el-select v-model="queryParams.onJobStatus" placeholder="请选择在职状态" clearable>
              <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['school:teacher:add']">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="upload" @click="handledBatchUpload" v-hasPermi="['school:teacher:add']">批量导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['school:teacher:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['school:teacher:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['school:teacher:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-loading="loading"
        :data="teacherList"
        @selection-change="handleSelectionChange"
        @header-click="handleCellMouseEnter"
        v-bind:border="showborder"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="教师姓名" align="center" prop="teacherName" v-if="columns[0].visible" />
        <el-table-column label="性别" align="center" prop="sex" v-if="columns[1].visible">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
          </template>
        </el-table-column>
        <el-table-column label="入职时间" align="center" prop="joinDate" width="180" v-if="columns[2].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.joinDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="民族" align="center" prop="nation" v-if="columns[3].visible">
          <template #default="scope">
            <dict-tag :options="nation" :value="scope.row.nation" />
          </template>
        </el-table-column>
        <el-table-column label="在岗状态" align="center" prop="onDutyStatus" v-if="columns[4].visible">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.onDutyStatus" />
          </template>
        </el-table-column>
        <el-table-column label="在职状态" align="center" prop="onJobStatus" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.onJobStatus" />
          </template>
        </el-table-column>
        <el-table-column label="主学科" align="center" prop="subjectName" v-if="columns[6].visible" />
        <el-table-column label="职位" align="center" prop="position" v-if="columns[7].visible" />
        <el-table-column label="手机号" align="center" prop="telphone" v-if="columns[8].visible" />
        <el-table-column label="省" align="center" prop="province" v-if="columns[9].visible" />
        <el-table-column label="市" align="center" prop="city" v-if="columns[10].visible" />
        <el-table-column label="区" align="center" prop="districts" v-if="columns[11].visible" />
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[12].visible" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['school:teacher:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['school:teacher:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改教师管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body>
      <el-form ref="teacherFormRef" :model="form" :rules="rules" :label-width="formLabelWidth">
        <campus @schoolCampus="handleSchoolCampus" :selectValue="form.schoolCampusId" :multiple="true"></campus>

        <el-row>
          <el-col :span="12">
            <el-form-item label="教师姓名" prop="teacherName">
              <el-input v-model="form.teacherName" placeholder="请输入教师姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入职时间" prop="joinDate">
              <el-date-picker clearable v-model="form.joinDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择入职时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="民族" prop="nation">
              <el-select v-model="form.nation" placeholder="请选择民族">
                <el-option v-for="dict in nation" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="在岗状态" prop="onDutyStatus">
              <el-radio-group v-model="form.onDutyStatus">
                <el-radio v-for="dict in sys_yes_no" :key="dict.value" :label="dict.value">{{dict.label}} </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="在职状态" prop="onJobStatus">
              <el-radio-group v-model="form.onJobStatus">
                <el-radio v-for="dict in sys_yes_no" :key="dict.value" :label="dict.value">{{dict.label}} </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row> </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="telphone">
              <el-input v-model="form.telphone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="form.position" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="主学科" prop="mainDisciplineId">
              <el-select v-model="form.mainDisciplineId" placeholder="请选择主学科" @change="handleChangemainDiscipline" clearable>
                <el-option
                  v-for="discipline in disciplines"
                  :key="discipline.disciplineId"
                  :label="discipline.subjectName"
                  :value="discipline.disciplineId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="16">
            <el-form-item label="副学科" prop="subDisciplineId">
              <el-select
                v-model="form.subDisciplineId"
                placeholder="请选择副学科"
                @change="handleChangesubDiscipline"
                multiple
                style="width:300px"
                clearable
              >
                <el-option
                  v-for="discipline in disciplines"
                  :key="discipline.disciplineId"
                  :label="discipline.subjectName"
                  :value="discipline.disciplineId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <el-form-item label="籍贯">
              <el-cascader
                style="width: 300px"
                v-model="form.nativePlace"
                :options="options"
                :props="{ value: 'label', label: 'label', expandTrigger: 'hover' }"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <ExcelUpload
      @upload-success="handleUpladeResult"
      @upload-cancel="handleCancel"
      :title="title"
      :objectName="objectName"
      :templatePath="templatePath"
      :contentType="contentType"
      v-model="batchImport"
      :uploadPath="uploadPath"
      :size="10"
    ></ExcelUpload>


  </div>

</template>

<script setup name="Teacher" lang="ts">
import {
    listTeacher,
    getTeacher,
    delTeacher,
    addTeacher,
    updateTeacher
} from '@/api/school/teacher';
import {
        TeacherVO,
        TeacherQuery,
        TeacherForm
} from '@/api/school/teacher/types';

import {
    listDiscipline
} from '@/api/school/discipline';
import campus from '@/components/campus/index.vue';
import ExcelUpload from '@/components/ExcelUpload/index.vue';
import { regionData } from 'element-china-area-data'
import { phone } from '@/utils/validate'
import { DisciplineForm, DisciplineVO } from '@/api/school/discipline/types';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
    const { sys_yes_no, sys_user_sex, nation } = toRefs<any>(proxy?.useDict('sys_yes_no', 'sys_user_sex', 'nation'));

const teacherList = ref<TeacherVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const names =  ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const formLabelWidth = '120px';
const showborder = ref(false)
const options = ref(regionData);
const queryFormRef = ref<ElFormInstance>();
const teacherFormRef = ref<ElFormInstance>();


const title = ref("");

//excel导入相关
const batchImport = ref(false);
// const bucketName = ref("templates")
const objectName = ref("教师管理导入模板.xls")
const templatePath = ref("school/teacher/importTemplate");
const contentType = ref("application/octet-stream")
const uploadPath = ref("school/teacher/upload");


const disciplines =  ref<DisciplineVO[]>([]);


const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const initFormData: TeacherForm = {
                    schoolCampusId: undefined,
                    teacherId: undefined,
                    teacherName: undefined,
                    sex: undefined,
                    joinDate: undefined,
                    nation: undefined,
                    onDutyStatus: undefined,
                    onJobStatus: undefined,
                    mainDisciplineId: undefined,
                    subDisciplineId: undefined,
                    position: undefined,
                    telphone: undefined,
                    province: undefined,
                    city: undefined,
                    districts: undefined,
                    remark: undefined
}
const data = reactive<PageData<TeacherForm, TeacherQuery>>({
    form: {...initFormData},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
                        teacherName: undefined,
                        sex: undefined,
                        joinDate: undefined,
                        nation: undefined,
                        onDutyStatus: undefined,
                        onJobStatus: undefined,
                        mainDisciplineId: undefined,
                        position: undefined,
                        telphone: undefined,
                        province: undefined,
                        city: undefined,
                        districts: undefined,
                        schoolCampusId: undefined,
        params: {
        }
    },
    rules: {

        schoolCampusId: [{ required: true, message: "请选择所属校区", trigger: "blur" }],
        teacherName: [{ required: true, message: "教师姓名不能为空", trigger: "blur" },
        { min: 2, message: "名字长度有误！" },
        { max: 20, message: "名字长度有误！" }],
        telphone: [
            { required: true, message: "手机号不能为空", trigger: "blur" },
            { validator: phone, message: "请输入正确的手机号！", trigger: "blur" },],
        mainDisciplineId: [{ required: true, message: "请选择主学科", trigger: "blur" }],

    }
});



const {queryParams, form, rules} = toRefs(data);

/** 查询教师管理列表 */
const getList = async () => {
    loading.value = true;
    const res = await listTeacher(queryParams.value);
        teacherList.value = res.rows;
    total.value = res.total;
    loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
    form.value = {...initFormData};
        teacherFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: TeacherVO[]) => {
    ids.value = selection.map(item => item.teacherId);
    names.value = selection.map(item => item.teacherName);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加教师管理";
      getDiscipline()
}

/** 修改按钮操作 */
const handleUpdate = async (row?: TeacherVO) => {
    reset();
    const _teacherId = row?.teacherId || ids.value[0]
    const res = await getTeacher(_teacherId);
    Object.assign(form.value, res.data);
        let array = [];
        array.push(res.data.province)
        array.push(res.data.city)
        array.push(res.data.districts)
        data.form.nativePlace = array
    dialog.visible = true;
    dialog.title = "修改教师管理";
      getDiscipline();
}


/** 提交按钮 */
const submitForm = () => {
        teacherFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.teacherId) {
                await updateTeacher(form.value).finally(() =>  buttonLoading.value = false);
            } else {
                await addTeacher(form.value).finally(() =>  buttonLoading.value = false);
            }
            proxy?.$modal.msgSuccess("修改成功");
            dialog.visible = false;
            await getList();
        }
    });
}

/** 删除按钮操作 */
const handleDelete = async (row?: TeacherVO) => {
    const _teacherIds = row?.teacherId || ids.value;
     const _subjectNames = row?.teacherName || names.value;
    await proxy?.$modal.confirm('是否确认删除教师"' + _subjectNames + '"的数据项？').finally(() => loading.value = false);
    await delTeacher(_teacherIds);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
    proxy?.download('school/teacher/export', {
        ...queryParams.value
    }, `teacher_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
    getList();
});


/** 列信息 */
const columns = ref([
            {key: 0, label: `教师姓名`, visible: true},
            {key: 1, label: `性别`, visible: true},
            {key: 2, label: `入职时间`, visible: true},
            {key: 3, label: `民族`, visible: true},
            {key: 4, label: `在岗状态`, visible: true},
            {key: 5, label: `在职状态`, visible: true},
            {key: 6, label: `主学科`, visible: true},
            {key: 7, label: `职位`, visible: true},
            {key: 8, label: `手机号`, visible: true},
            {key: 9, label: `省`, visible: true},
            {key: 10, label: `市`, visible: true},
            {key: 11, label: `区`, visible: true},
            {key: 12, label: `备注`, visible: true},
]);


function handleCellMouseEnter() {
    showborder.value = !showborder.value;
}


function searchhandleSchoolCampus(value: number|undefined) {
 data.queryParams.schoolCampusId = value;
}

function handledBatchUpload() {
    title.value = "批量导入学科";
    batchImport.value = true;
}


/**
 * 从 campus组件中获取校区
 * @param {*} value
 */
function handleSchoolCampus(value: number | undefined) {

     data.form.schoolCampusId = value;

}


function handleChangemainDiscipline() {
    let main = data.form.mainDisciplineId;
    let sub = data.form.subDisciplineId;
    console.log(sub)
    if(sub!=undefined){
    data.form.subDisciplineId = sub.filter(i => i != main)
    }

}


function handleChangesubDiscipline() {
    let sub = data.form.subDisciplineId;
    if (sub && Array.isArray(sub)) {
    if (sub.includes( data.form.mainDisciplineId)) {
      data.form.mainDisciplineId = "";
    }
  }
}

function handleUpladeResult(value: any) {
    if (value) {
        batchImport.value = false;
        getList();
    }
}
function handleCancel(value: boolean) {
    batchImport.value = value;
}

function getDiscipline() {
    listDiscipline().then(response => {


disciplines.value = response.rows.reduce((acc: DisciplineVO[], item) =>
  acc.some(d => d.subjectName === item.subjectName) ? acc : [...acc, item], []
);
console.log( disciplines.value)

    })

}
</script>
